<template>
    <div>
        <!--用于添加或修改的表单-->
        <el-dialog title="编辑字典数据" :visible.sync="dialogFormVisible">
            <el-form :model="sysDictData" :rules="rules" status-icon ref="sysDictData">
                <el-form-item label="字典类型">
                    <el-input v-model="sysDictData.dictType" autocomplete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="数据标签" prop="dictLabel">
                    <el-input v-model="sysDictData.dictLabel" autocomplete="off" placeholder="请输入数据标签"></el-input>
                </el-form-item>
                <el-form-item label="数据键值" prop="dictValue">
                    <el-input v-model="sysDictData.dictValue" autocomplete="off" placeholder="请输入数据键值"></el-input>
                </el-form-item>
                <el-form-item label="样式属性">
                    <el-input v-model="sysDictData.cssClass" autocomplete="off" placeholder="请输入样式属性"></el-input>
                </el-form-item>
                <el-form-item label="显示排序" prop="dictSort">
                    <el-input-number v-model="sysDictData.dictSort" controls-position="right"
                                     :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="回显样式">
                    <el-select v-model="sysDictData.listClass" filterable>
                        <el-option
                                v-for="item in listClassList"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="sysDictData.status">
                        <el-radio :label=0>正常</el-radio>
                        <el-radio :label=1>停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="sysDictData.remark">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel('sysDictData')">取 消</el-button>
                <el-button type="primary" @click="editForm('sysDictData')">确 定</el-button>
            </div>
        </el-dialog>

        <!--字典名称下拉框-->
        <span class="font">字典名称</span>
        <el-select v-model="dictData.dictName" filterable placeholder="请选择字典名称" size="mini">
            <el-option
                    v-for="item in dictTypeList"
                    :key="item.dictName"
                    :label="item.dictName"
                    :value="item.dictName">
            </el-option>
        </el-select>
        <!--字典标签输入框-->
        <span class="font" style="margin: 10px">字典标签</span>
        <el-autocomplete
                v-model="dictData.dictLabel"
                :fetch-suggestions="querySearchForDictLabel"
                placeholder="请输入字典标签"
                clearable
                prefix-icon="el-icon-search"
                size="mini"
                style="cursor: text;margin-top: 10px;margin-left: 10px"
        >
        </el-autocomplete>
        <!--下拉选项框（status）-->
        <span class="font" style="margin: 10px">状态</span>
        <el-select v-model="dictData.status" clearable placeholder="请选择状态" size="mini">
            <el-option
                    v-for="item in statuses"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
            </el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="search" style="margin-left: 10px">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>

        <br>
        <!--按钮区-->
        <el-row style="display: inline-block; margin-right: 15px;margin-top: 10px">
            <el-button type="primary" class="el-icon-plus" size="mini" plain @click="handleEdit('sysDictData')">新增
            </el-button>
        </el-row>

        <el-row style="display: inline-block; margin-right: 15px;margin-top: 10px">
            <el-button type="success" class="el-icon-edit" size="mini" :disabled="disableEdit" @click="showForm">修改
            </el-button>
        </el-row>

        <el-row style="display: inline-block; margin-right: 15px;margin-top: 10px">
            <el-popconfirm
                    confirm-button-text='好的'
                    cancel-button-text='不用了'
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定要删除这些吗？"
                    @confirm="deletes"
                    @cancel="cancelDelete"
            >
                <el-button type="danger" class="el-icon-delete" size="mini" :disabled=disableDelete slot="reference">删除
                </el-button>
            </el-popconfirm>
        </el-row>

        <el-row style="display: inline-block; margin-right: 15px;margin-top: 10px">
            <el-button type="warning" class="el-icon-download" size="mini" plain @click="exportExcel">导出</el-button>
        </el-row>

        <!--分页显示-->
        <el-table
                :data="sysDictDatas"
                style="width: 100%" @select="checked" @select-all="checkAll">
            <el-table-column
                    type="selection">
            </el-table-column>
            <el-table-column
                    label="字典编码"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.dictCode }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="字典标签"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">
                        <el-tag v-if="scope.row.listClass == ''">{{ scope.row.dictLabel}}</el-tag>
                        <el-tag v-if="scope.row.listClass == 'primary'">{{ scope.row.dictLabel}}</el-tag>
                        <el-tag type="danger" v-if="scope.row.listClass == 'danger'">{{ scope.row.dictLabel}}</el-tag>
                        <el-tag type="warning" v-if="scope.row.listClass == 'warning'">{{ scope.row.dictLabel}}</el-tag>
                        <el-tag type="info" v-if="scope.row.listClass == 'info'">{{ scope.row.dictLabel}}</el-tag>
                        <el-tag type="success" v-if="scope.row.listClass == 'success'">{{ scope.row.dictLabel}}</el-tag>
                        </span>
                </template>
            </el-table-column>
            <el-table-column
                    label="字典键值"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.dictValue }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="字典排序"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.dictSort }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="状态"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">
                        <el-tag v-if="scope.row.status == 0">正常</el-tag>
                        <el-tag type="danger" v-if="scope.row.status == 1">停用</el-tag>
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                    label="备注"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.remark }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="创建时间"
                    width="180" align="center">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="showForm(scope.$index, scope.row)">修改
                    </el-button>
                    <el-popconfirm
                            confirm-button-text='是的'
                            cancel-button-text='不用了'
                            icon="el-icon-info"
                            icon-color="red"
                            title="确定要删除吗？"
                            @confirm="handleDelete(scope.$index, scope.row)"
                            @cancel="cancelDelete"
                    >
                        <el-button
                                slot="reference"
                                size="mini"
                                type="danger">删除
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!--分页控件-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="current"
                :page-sizes="[10, 15, 20]"
                :page-size="100"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total" align="right">
        </el-pagination>
    </div>
</template>

<script>
    let isUpdate = false;
    export default {
        name: "DictionaryData",
        data() {
            let validateDictLabel = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('数据标签不能为空'));
                } else {
                    callback();
                }
            };
            let validateDictValue = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('数据键值不能为空'));
                } else {
                    callback();
                }
            };
            return {
                //所有listClass
                listClassList: [],
                //所有的dictType数据(用于显示输入框提示)
                dictTypeInput: [],
                //下拉框集合
                dictTypeList: [],
                //用于查询的对象
                dictData: {
                    dictName: this.$route.params.dictName,
                    dictLabel: "",
                    status: ""
                },
                statuses: [
                    {value: 0, label: "正常"},
                    {value: 1, label: "停用"}
                ],
                //当前页数
                current: 1,
                //总条数
                total: 0,
                //每页显示多少条（默认10条）
                size: 10,
                //用于显示表格数据
                sysDictDatas: [],
                //用于添加或修改的对象
                sysDictData: {
                    dictCode: '',
                    dictSort: 0,
                    dictLabel: '',
                    dictValue: '',
                    dictType: this.$route.params.dictType,
                    cssClass: '',
                    listClass: 'primary',
                    isDefault: 'Y',
                    status: 0,
                    remark: '',
                    createBy: '',
                    updateBy: ''
                },
                dialogFormVisible: false,
                //规则
                rules: {
                    dictLabel: [
                        {required: true, validator: validateDictLabel, trigger: 'blur'}
                    ],
                    dictValue: [
                        {required: true, validator: validateDictValue, trigger: 'blur'}
                    ],
                    dictSort: [
                        {required: true, trigger: 'blur'}
                    ]
                },
                //是否禁用多删
                disableDelete: true,
                //是否禁用修改
                disableEdit: true,
                //选中的行
                selections: []
            }
        },
        methods: {
            querySearchForDictLabel(queryString, cb) {
                let dictTypeInput = this.dictTypeInput;
                let results = (queryString ? dictTypeInput.filter(this.createFilterForDictLabel(queryString)) : dictTypeInput).map(
                    item => {
                        return {
                            value: item.dictLabel
                        }
                    }
                );
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            //定义过滤规则
            createFilterForDictLabel(queryString) {
                return (item) => {
                    return (item.dictLabel.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            //获取所有的DictData给dictTypeInput数组赋值
            loadAll() {
                this.axios.get("http://localhost:8080/SysDictData").then(
                    res => {
                        this.dictTypeInput = res.data.data;
                    }
                );
                this.axios.get("http://localhost:8080/SysDictType").then(
                    res => {
                        this.dictTypeList = res.data.data;
                    }
                );
                this.axios.get("http://localhost:8080/sysDictData/listClass").then(
                    res => {
                        this.listClassList = res.data.data;
                    }
                )
            },
            //模糊查询/分页查询
            search() {
                this.current = 1;
                this.axios.get("http://localhost:8080/SysDictDatas/page/fuzzy?current=" + this.current + "&dictName=" + this.dictData.dictName
                    + "&dictLabel=" + this.dictData.dictLabel + "&status=" + this.dictData.status + "&size=" + this.size).then(
                    res => {
                        this.sysDictDatas = res.data.data.records;
                        this.current = res.data.data.current;
                        this.total = res.data.data.total;
                        this.size = res.data.data.size;
                    }
                )
            },
            //重置
            reset() {
                this.dictData = {
                    dictName: this.$route.params.dictName,
                    dictLabel: "",
                    status: ""
                };
                this.current = 1;
                this.size = 10;
                this.search();
            },
            //处理size变化的函数
            handleSizeChange(val) {
                this.size = val;
                this.search();
            },
            //处理当前页变化的函数
            handleCurrentChange(current) {
                this.current = current;
                this.axios.get("http://localhost:8080/SysDictDatas/page/fuzzy?current=" + this.current + "&dictName=" + this.dictData.dictName
                    + "&dictLabel=" + this.dictData.dictLabel + "&status=" + this.dictData.status + "&size=" + this.size).then(
                    res => {
                        this.sysDictDatas = res.data.data.records;
                        this.current = res.data.data.current;
                        this.total = res.data.data.total;
                        this.size = res.data.data.size;
                    }
                );
                this.disableDelete = true;
                this.disableEdit = true;
            },
            //显示表单
            handleEdit(formName) {
                isUpdate = false;
                this.dialogFormVisible = true;
                this.sysDictData = {
                    dictCode: '',
                    dictSort: 0,
                    dictLabel: '',
                    dictValue: '',
                    dictType: this.$route.params.dictType,
                    listClass: '',
                    isDefault: 'Y',
                    status: 0,
                    remark: '',
                    createBy: '',
                    updateBy: ''
                };
                //    新增前清空表单
                this.$refs[formName].resetFields();
            },
            //修改回显
            showForm(index, row) {
                this.dialogFormVisible = true;
                isUpdate = true;
                this.sysDictData = JSON.parse(JSON.stringify(row));
                this.sysDictData.status = Number(row.status);
            },
            //取消
            cancel(formName) {
                this.dialogFormVisible = false;
                this.$refs[formName].resetFields();
            },
            //添加或修改
            editForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (!isUpdate) {
                            this.sysDictData.createBy = localStorage.getItem("username");
                            this.axios.post("http://localhost:8080/sysDictData", this.sysDictData).then(
                                res => {
                                    if (res.data.data == 'OK') {
                                        this.$message({
                                            message: '添加成功！',
                                            type: 'success'
                                        });
                                        this.search();
                                    } else {
                                        this.$message({
                                            message: '添加失败！',
                                            type: 'error'
                                        });
                                    }
                                }
                            );
                            //    修改
                        } else {
                            this.sysDictData.updateBy = localStorage.getItem("username");
                            this.axios({
                                url: "http://localhost:8080/sysDictData",
                                method: "put",
                                data: {
                                    dictCode: this.sysDictData.dictCode,
                                    dictSort: this.sysDictData.dictSort,
                                    dictLabel: this.sysDictData.dictLabel,
                                    dictValue: this.sysDictData.dictValue,
                                    dictType: this.sysDictData.dictType,
                                    listClass: this.sysDictData.listClass,
                                    isDefault: this.sysDictData.isDefault,
                                    cssClass: this.sysDictData.cssClass,
                                    status: this.sysDictData.status,
                                    remark: this.sysDictData.remark,
                                    updateBy: this.sysDictData.updateBy
                                }
                            }).then(
                                res => {
                                    if (res.data.data == 'OK') {
                                        this.$message({
                                            message: '修改成功！',
                                            type: 'success'
                                        });
                                        this.search();
                                    } else {
                                        this.$message({
                                            message: res.data.data,
                                            type: 'error'
                                        });
                                    }
                                }
                            );
                            isUpdate = false;
                        }
                        this.dialogFormVisible = false;
                    } else {
                        return false;
                    }
                });
            },
            //删除方法
            handleDelete(index, row) {
                this.axios.delete("http://localhost:8080/sysDictData/" + row.dictCode).then(
                    res => {
                        if (res.data.data == 'OK') {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            this.search();
                        } else {
                            this.$message({
                                message: res.data.data,
                                type: 'error'
                            });
                        }
                    }
                )
                this.disableDelete = true;
                this.selections = [];
            },
            //多删
            deletes() {
                this.axios({
                    method: 'delete',
                    url: "http://localhost:8080/sysDictData/delete",
                    data: this.selections
                }).then(
                    res => {
                        if (res.data.data == 'OK') {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            this.search();
                        } else {
                            this.$message({
                                message: res.data.data,
                                type: 'error'
                            });
                        }
                    }
                );
                this.disableDelete = true;
                this.selections = [];
            },

            //导出excel
            exportExcel() {
                this.axios({
                    method: "post",
                    url: "http://localhost:8080/sysDictData/export", // 请求地址
                    data: this.sysDictDatas, // 参数
                    responseType: 'blob' // 表明返回服务器返回的数据类型
                }).then(
                    res => {
                        if (res && res.data) {
                            // 调用js-file-download下载文件，第一个参数是数据流，第二个参数是文件名，我这后端返回时把文件名放到响应的header的filename字段中，所以用这种方式取出
                            this.jsFileDownload(res.data, decodeURIComponent("字典数据.xlsx"))
                        }
                    }
                )
            },
            //选中选项的事件方法
            checked(selection, row) {
                this.selections = selection;
                if (selection.length === 1) {
                    this.disableEdit = false;
                } else {
                    this.disableEdit = true;
                }
                if (selection.length >= 1) {
                    this.disableDelete = false;
                } else {
                    this.disableDelete = true;
                }
            },
            //全选按钮事件方法
            checkAll(selection) {
                this.selections = selection;
                if (selection.length === 1) {
                    this.disableEdit = false;
                } else {
                    this.disableEdit = true;
                }
                if (selection.length >= 1) {
                    this.disableDelete = false;
                } else {
                    this.disableDelete = true;
                }
            },
            //取消删除时
            cancelDelete() {
                this.$message({
                    message: '取消删除',
                });
            }
        },
        created() {
            this.search();
        },
        mounted() {
            this.loadAll();
        }
    }
</script>

<style scoped>
    .font {
        font-size: 15px;
        font-weight: 700;
        color: #606266
    }
</style>